package com.cskaoyan.shopping.converter;


import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.dto.UpdateCartNumRequest;
import com.cskaoyan.shopping.form.CartForm;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Component
public class CartItemConverter {
    /**
     *  将Item对象转换为CartProductDto对象
     * @param item
     * @author ycc
     * @since 2022/07/30 15:05
     */
    public static CartProductDto item2Dto(Item item){
        CartProductDto cartProduct =new CartProductDto();
        cartProduct.setProductId(item.getId());
        cartProduct.setProductName(item.getTitle());
        cartProduct.setSalePrice(item.getPrice());
        cartProduct.setProductImg(item.getImages()[0]);
        cartProduct.setProductNum(item.getNum().longValue());
        if(item.getLimitNum()==null){
            cartProduct.setLimitNum(Long.valueOf(item.getNum()));
        }else if(item.getLimitNum()<0&&item.getNum()<0) {
            cartProduct.setLimitNum((long) 10);
        }else{
            cartProduct.setLimitNum(Long.valueOf(item.getLimitNum()));
        }
        return cartProduct;
    }

    /**
     * 将CartForm象转换为UpdateCartNumRequest对象
     * @param cartForm 
     * @author ycc
     * @since 2022/07/30 15:08 
     */
    public static <T> T cartFormToTarget(CartForm cartForm, T t){
        Class<?> aClass = t.getClass();
        try {
            Method[] methods = aClass.getDeclaredMethods();
            for (Method method : methods) {
                method.setAccessible(true);
                if (method.getName().equals("setUserId")) {
                    method.invoke(t,cartForm.getUserId());
                }
                if (method.getName().equals("setItemId")) {
                    method.invoke(t,cartForm.getProductId());
                }
                if (method.getName().equals("setNum")) {
                    method.invoke(t,cartForm.getProductNum());
                }
                if (method.getName().equals("setChecked")) {
                    method.invoke(t,cartForm.getChecked());
                }
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return t;
    }
}
